config = require('../config')
Schema = config.Schema
modeldb = config.modeldb
gridfs = new (require('../services/gridfs').FileStoreService)(config.fsdb.db)
ObjectId = require('mongoose').Types.ObjectId
fsdb = require('../config').fsdb.db


Image = require('../models/image').Image
dataPage = require('../services/dataPage').queryPage
resErr = require('./util').resErr
common_util = require('../services/common_util')
_ = require('underscore')
file_util = require('../services/file_util')






exports.image_add = (req,res) ->
  title = common_util.trim(req.param('title'))
  code = common_util.trim(req.param('code'))
  if _.isNull(title) || _.isUndefined(title)
    return resErr res,'图片标题不能为空！'
  if _.isNull(code) || _.isUndefined(code)
    return resErr res,'图片编号不能为空！'
  if !req.param('image_file_id')
    return resErr(res,"请先上传图片再保存！")

  Image.count {"code":code},(err,count) ->
    if err
      return resErr res,err
    if count > 0
      return resErr res,'图片编号已存在'
    image = new Image
    image.add req,(err) ->
      if err
        return resErr(res,err)
      res.json({'success':true})


exports.image_list = (req,res) ->
  params = {}
  #相当于sql里面like的写法
  params.title = {'$regex': req.param("title")}  unless !req.param("title")
  params.code = {'$regex' : req.param("code")} unless !req.param("code")
  sorts = {}  
  sort = req.param('sort')
  dir = req.param('dir')
  if dir && sort
    dir = if dir.toUpperCase() == 'ASC' then 1 else -1
    sorts[sort] = dir
  else
    sorts.update_at = -1
  dataPage Image,params,sorts,req.param("pageSize") or req.param("limit"),req.param("pageNum") or req.param("page"), (err,results) ->
    if err
      return resErr res,err
    res.json(results)


exports.image_detail = (req,res) ->
  _id = req.param("_id")
  if !_id
    return resErr res,'编码不得为空！'
  Image.findById _id,(err,result) ->
    if err
      return resErr(res,err)
    res.json(result)

exports.image_edit = (req,res) ->
  title = common_util.trim(req.param('title'))
  code = common_util.trim(req.param('code'))
  _id = req.param('_id')
  if !_id
    return resErr res,'编码不得为空！'
  if _.isNull(title) || _.isUndefined(title)
    return resErr res,'图片标题不能为空！'
  if _.isNull(code) || _.isUndefined(code)
    return resErr res,'图片编号不能为空！'
  if !req.param('image_file_id')
    return resErr(res,"请先上传图片再保存！")

  Image.count {"_id":{"$ne":_id},"code":code},(err,count) ->
    if err
      return resErr(res,err)
    if count > 0
      return resErr(res,'图片编号已存在')
    params = {}
    params.title = title
    params.code = code
    params.image_file_id = req.param('image_file_id')
    params.update_at = new Date
    Image.findByIdAndUpdate _id,params,(err) ->
      if err
        return resErr(res,err)
      res.json({'success':true})


exports.image_del = (req,res) ->
  _id = req.param('_id')
  if !_id
    return resErr(res,'编码不得为空')
  Image.findById _id, (err,doc) ->
    if err
      return resErr res,err
    gridfs_id = doc.file_id
    Image.findByIdAndRemove _id,(err)->
      if err
        return resErr res,err
      file_util.delete_by_file_id gridfs_id,(err) ->
        if err
          return resErr res,err
        res.json({'success':true})



exports.image_view = (req,res) ->
  _src = ''
  code = req.param('code')
  if _.isNull(code) || _.isUndefined(code)
    return resErr res,'图片编号不得为空！'
  Image.findOne {'code':code},(err,img) ->
    if err
      return resErr res,err
    if !img
      return resErr res,'图片编号不存在！'
    if /^[0-9a-fA-F]+$/.test(img.image_file_id)
      _src = new ObjectId(img.image_file_id)
    if !_src
      return resErr res,'文件id不合法！'
    gridfs.readFile _src, (err,contentType,filename, gs) ->
      if err
        return resErr res,err
      if contentType && contentType.match(/^image\//)
        res.header("Content-Type",contentType)

      try
        gs.stream(false).pipe(res)
      catch ex
        return resErr(res,ex)
      finally
        gs.close()